package com.zk.study.curator;

import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.util.concurrent.TimeUnit;

/**
 * @Author：Administrator
 * @Date：2022/7/7/0007 20:34
 * @Versiion：1.0
 */
@Slf4j
public class TicketService implements Runnable {

    private volatile int ticket_count = 15;

    private InterProcessMutex lock;

    public TicketService() {
        ExponentialBackoffRetry retry = new ExponentialBackoffRetry(3 * 1000, 5);
        //创建客户端对象
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString("192.168.3.53:2181")
                .sessionTimeoutMs(60 * 1000)
                .connectionTimeoutMs(15 * 1000)
                .retryPolicy(retry)
                .build();
        client.start();
        lock = new InterProcessMutex(client,"/lock");
    }

    @Override
    public void run() {
        while (true) {
            try {
                //加锁
                lock.acquire(3, TimeUnit.SECONDS);
                if (ticket_count > 0) {
                    System.out.println("线程  "  + Thread.currentThread().getName() +" 购票: "+ticket_count);
                    ticket_count -= 1;
                } else {
                    return;
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    //释放锁
                    lock.release();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
